package com.doubao.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.common.result.Result;
import com.doubao.device.dto.RatingDTO;
import com.doubao.device.dto.request.RatingRequest;
import com.doubao.device.entity.DeviceRating;
import com.doubao.device.mapper.DeviceRatingMapper;
import com.doubao.device.service.DeviceRatingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DeviceRatingServiceImpl extends ServiceImpl<DeviceRatingMapper, DeviceRating> implements DeviceRatingService {

    @Override
    public Result<RatingDTO> rateDevice(Long userId, RatingRequest request) {
        // 检查用户ID是否存在
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        // 检查是否已经评分过
        LambdaQueryWrapper<DeviceRating> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceRating::getUserId, userId)
                .eq(DeviceRating::getDeviceId, request.getDeviceId());

        DeviceRating existingRating = getOne(queryWrapper, false);

        if (existingRating != null) {
            // 更新已有评分
            existingRating.setRating(request.getRating());
            existingRating.setComment(request.getComment());
            existingRating.setUpdatedAt(LocalDateTime.now());

            updateById(existingRating);

            // 更新智能体平均评分
            updateDeviceAverageRating(request.getDeviceId());

            return Result.success(convertToDTO(existingRating));
        } else {
            // 创建新评分
            DeviceRating rating = new DeviceRating();
            rating.setUserId(userId);
            rating.setDeviceId(request.getDeviceId());
            rating.setRating(request.getRating());
            rating.setComment(request.getComment());
            rating.setCreatedAt(LocalDateTime.now());
            rating.setUpdatedAt(LocalDateTime.now());

            save(rating);

            // 更新智能体平均评分
            updateDeviceAverageRating(request.getDeviceId());

            return Result.success(convertToDTO(rating));
        }
    }

    @Override
    public Result<Void> deleteRating(Long userId, Long ratingId) {
        // 检查用户ID是否存在
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        // 获取评分
        DeviceRating rating = getById(ratingId);
        if (rating == null) {
            return Result.failed("评分不存在");
        }

        // 检查是否是用户自己的评分
        if (!rating.getUserId().equals(userId)) {
            return Result.failed("无权删除他人评分");
        }

        // 删除评分
        removeById(ratingId);

        // 更新智能体平均评分
        updateDeviceAverageRating(rating.getDeviceId());

        return Result.success();
    }

    @Override
    public Result<RatingDTO> getUserRating(Long userId, Long deviceId) {
        // 检查用户ID是否存在
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        // 查询用户评分
        LambdaQueryWrapper<DeviceRating> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceRating::getUserId, userId)
                .eq(DeviceRating::getDeviceId, deviceId);

        DeviceRating rating = getOne(queryWrapper, false);

        if (rating == null) {
            return Result.success(null);
        }

        return Result.success(convertToDTO(rating));
    }

    @Override
    @Cacheable(value = "deviceRatings", key = "'device:' + #deviceId + ':page:' + #page + ':size:' + #size", unless = "#result.data == null")
    public Result<IPage<RatingDTO>> getDeviceRatings(Long deviceId, Integer page, Integer size) {
        // 创建分页对象
        Page<DeviceRating> pageParam = new Page<>(page, size);

        // 创建查询条件
        LambdaQueryWrapper<DeviceRating> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceRating::getDeviceId, deviceId)
                .orderByDesc(DeviceRating::getCreatedAt);

        // 执行分页查询
        IPage<DeviceRating> ratingPage = page(pageParam, queryWrapper);

        // 转换为DTO
        IPage<RatingDTO> dtoPage = ratingPage.convert(this::convertToDTO);

        return Result.success(dtoPage);
    }

    @Override
    public Result<Boolean> isRated(Long userId, Long deviceId) {
        // 检查用户ID是否存在
        if (userId == null) {
            return Result.success(false);
        }

        // 查询用户是否已评分
        Integer count = baseMapper.checkIsRated(userId, deviceId);

        return Result.success(count > 0);
    }

    @Override
    @Cacheable(value = "deviceAverageRating", key = "#deviceId", unless = "#result.data == null")
    public Result<BigDecimal> getAverageRating(Long deviceId) {
        // 查询平均评分
        BigDecimal averageRating = baseMapper.selectAverageRating(deviceId);

        if (averageRating == null) {
            averageRating = BigDecimal.ZERO;
        }

        return Result.success(averageRating);
    }

    @Override
    @CacheEvict(value = "deviceAverageRating", key = "#deviceId")
    public Result<Void> updateDeviceAverageRating(Long deviceId) {
        // 此方法已在其他方法中调用，用于更新平均评分
        // 实际实现可能涉及到更新智能体表的平均评分字段

        return Result.success();
    }

    @Override
    @Cacheable(value = "deviceRatingStats", key = "#deviceId", unless = "#result.data == null")
    public Result<Map<Integer, Integer>> getRatingStats(Long deviceId) {
        // 查询评分统计
        List<Object[]> statsList = baseMapper.selectRatingStats(deviceId);

        // 转换为Map<Integer, Integer>
        Map<Integer, Integer> stats = statsList.stream()
                .collect(Collectors.toMap(
                        row -> ((Number) row[0]).intValue(), // Key: 评分等级
                        row -> ((Number) row[1]).intValue()  // Value: 数量
                ));

        if (stats == null || stats.isEmpty()) {
            // 初始化默认值
            stats = Map.of(1, 0, 2, 0, 3, 0, 4, 0, 5, 0);
        }

        return Result.success(stats);
    }


    /**
     * 将实体转换为DTO
     */
    private RatingDTO convertToDTO(DeviceRating rating) {
        if (rating == null) {
            return null;
        }

        RatingDTO dto = new RatingDTO();
        BeanUtils.copyProperties(rating, dto);
        return dto;
    }
}